package br.com.winesys.geta.report;

import java.awt.GraphicsEnvironment;
import java.awt.Window;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.commons.beanutils.PropertyUtils;

public abstract class JasperReportFilter<Filter> extends ReportFilter<Filter> {

	public JasperReportFilter(Window parent, String title) {
		super(parent, title);
	}

	@Override
	protected void doGenerate(Filter filter, List<?> objects) {
		InputStream report = null;
		try {
			if (filter.getClass().getDeclaredField("report") != null) {
				report = ((URL) PropertyUtils.getProperty(filter, "report")).openStream();
			}
			Map<String, Object> parameters = new HashMap<String, Object>();
			for (Field field : filter.getClass().getDeclaredFields()) {
				parameters.put(field.getName(), PropertyUtils.getProperty(filter, field.getName()));
			}
			final JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(objects);
			final JasperPrint print = JasperFillManager.fillReport(report, parameters, dataSource);
			final CustomJasperViewer viewer = new CustomJasperViewer(print, this.getDialog());
			viewer.setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
			viewer.setVisible(true);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
}
